public class Test8 {
    public static void main(String[] args) {
        char[][] grid = {{'1','1','0','0','0'}, {'1','1','0','0','0'}, {'0','0','1','0','0'}, {'0','0','0','1','1'}};
        numIslands(grid);
    }
    static int m, n;
    static boolean[][] vis;
    static int[] dx = {0, 0, 1, -1};
    static int[] dy = {1, -1, 0, 0};
    static int count = 0;
    public static int numIslands(char[][] grid) {
        m = grid.length;
        n = grid[0].length;
        vis = new boolean[m][n];
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == '1' && vis[i][j] == false) {
                    vis[i][j] = true;
                    count++;
                    dfs(grid, i, j);
                }
            }
        }
        return count;
    }
    public static void dfs(char[][] grid, int i, int j) {

        for(int k = 0; k < 4; k++) {
            int x = dx[k] + i;
            int y = dy[k] + j;
            if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' && vis[x][y] == false) {
                vis[x][y] = true;
                dfs(grid, x, y);
            }
        }
    }
}
